
/**
 * Project Name:cats-web
 * File Name:FileUploadController.java
 * Package Name:com.catsic.web.controllers
 * Copyright (c) 2014, oa.catsic.com All Rights Reserved.
 */
 
package com.catsic.pub.controllers;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.catsic.base.annotation.Log;
import com.catsic.base.controller.BaseController;
import com.catsic.base.exception.CatsicException;
import com.catsic.base.exception.CatsicExceptionCode;
import com.catsic.base.utils.FtpUtils;
import com.catsic.base.utils.SpringContextUtil;
import com.catsic.pub.condition.FileUploadCondition;
import com.catsic.pub.constants.Constants;
import com.catsic.pub.entity.FileUpload;
import com.catsic.pub.entity.Ftp;
import com.catsic.pub.file.service.FileUploadService;
import com.catsic.pub.ftp.service.FtpService;


/**
 * ClassName: FileUploadController
 * Description: 文件上传
 * author: yangyd
 */
@Controller
public class FileUploadController extends BaseController{
	@Autowired
	private FileUploadService fileService;
	
	@Autowired
	private FtpService ftpService;

	/**
	 * 文件上传
	 * @param id 相关业务ID
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/upload")
	@Log(module = "文件管理", operation = "上传文件")
    public void upload(String fid,String note,HttpServletRequest request,HttpServletResponse response) throws Exception {  
		try{
			/**
	         * 创建一个通用的多部分解析器  
	         */
	        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
	        /**
	         * 判断 request 是否有文件上传,即多部分请求  
	         */
	        if(multipartResolver.isMultipart(request)){  
	        	Ftp ftp = ftpService.findByOrganCode(SpringContextUtil.getMessage(Constants.行政区划));
        		FtpUtils ft = new FtpUtils(ftp.getFtpip(), ftp.getFtpport(), ftp.getFtpuser(), ftp.getFtppassword());
	            /**
	             * 转换成多部分request    
	             */
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; 
	            /**
	             * 取得request中的所有文件名 
	             */
	            Iterator<String> iter = multiRequest.getFileNames();  
	            while(iter.hasNext()){  
	                /**
	                 * 取得上传文件  
	                 */
	                MultipartFile file = multiRequest.getFile(iter.next());  
	            	/**
	            	 * 得到原文件名
	            	 */
	            	String fileName = file.getOriginalFilename();
	            	/**
	            	 * 上传至FTP的文件名
	            	 */
	            	String ftpFileName = RandomStringUtils.randomNumeric(16);
	            	
	            	/**
	            	 * 文件名后缀
	            	 */
	            	String suffix = fileName.substring(fileName.indexOf('.'));
	            	if(StringUtils.isNotBlank(fileName)){
	            		/**
	            		 *保存至本地
	            		 */
	/*            		File tempFile = new File(dir+File.separator+RandomStringUtils.randomNumeric(16));
	            		file.transferTo(tempFile);*/
	            		/**
	            		 *上传至FTP
	            		 */
	            		ft.upload(ftpFileName+suffix,file.getInputStream(),"");
	            		/**
	            		 *保存至数据库
	            		 */
	            		FileUpload fileEntity = new FileUpload();
	            		fileEntity.setFid(fid);
	            		fileEntity.setFileName(fileName);
	            		if (StringUtils.isNotEmpty(note)) {
	            			fileEntity.setDescription(note);
						}
	            		fileEntity.setRandomFileName(ftpFileName+suffix);
	            		fileService.add(fileEntity);
	            	}
	      
	            }
	        }
		}catch(CatsicException e){
			response.setStatus(500);
			throw e;
		}catch(Exception e){
			response.setStatus(500);
			throw new CatsicException(CatsicExceptionCode.FTP文件上传失败);
		}
    }

	/**
	 * 高拍仪上传
	 * @param fid
	 * @param note
	 * @param fileName
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@SuppressWarnings("null")
	@RequestMapping(value = "/uploadFile")
	@Log(module = "文件管理", operation = "上传文件")
    public void uploadFile(String fid,String note,String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception {  
		InputStream is = null;	
		if(StringUtils.isNotBlank(note)){
			note =URLDecoder.decode(request.getParameter("note"),"utf-8");
		}
		response.setCharacterEncoding("UTF-8");
		try{
			
        	/**
        	 * 上传至FTP的文件名
        	 */
        	String ftpFileName = RandomStringUtils.randomNumeric(16);
        	
        	/**
        	 * 文件名后缀
        	 */
        	String suffix = fileName.substring(fileName.indexOf('.'));
        	if(StringUtils.isNotBlank(fileName)){
        
        		/**
        		 *上传至FTP
        		 */
        		Ftp ftp = ftpService.findByOrganCode(SpringContextUtil.getMessage(Constants.行政区划));
        		FtpUtils ft = new FtpUtils(ftp.getFtpip(), ftp.getFtpport(), ftp.getFtpuser(), ftp.getFtppassword());
        		ft.upload(ftpFileName+suffix,request.getInputStream(),"");
        		/**
        		 *保存至数据库
        		 */
        		FileUpload fileEntity = new FileUpload();
        		fileEntity.setFid(fid);
        		fileEntity.setFileName(fileName);
        		if (StringUtils.isNotEmpty(note)) {
        			fileEntity.setDescription(note);
				}
        		fileEntity.setRandomFileName(ftpFileName+suffix);
        		fileService.add(fileEntity);
        	}
		}catch(CatsicException e){
			response.setStatus(500);
			throw e;
		}catch(Exception e){
			response.setStatus(500);
			throw new CatsicException(CatsicExceptionCode.FTP文件上传失败);
		}finally{
			is.close();
		}
   	}
	
	/**
	 * 文件下载
	 * @param id 文件ID
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/download")
	@Log(module = "文件管理", operation = "下载文件")
    public void download(String id) throws Exception{
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
		FileUpload file = fileService.findById(id);
		response.setContentType("text/html;charset=utf-8");  
        request.setCharacterEncoding("utf-8");
		/**
		 * 弹出下载对话框的关键代码
		 */
		response.setHeader(
				"Content-disposition",
				"attachment;filename="
						+ URLEncoder.encode(file.getFileName(), "utf-8"));
		Ftp ftp = ftpService.findByOrganCode(SpringContextUtil.getMessage(Constants.行政区划));
		FtpUtils ft = new FtpUtils(ftp.getFtpip(), ftp.getFtpport(), ftp.getFtpuser(), ftp.getFtppassword());
		OutputStream outputStream = response.getOutputStream();
		ft.download(file.getRandomFileName(),outputStream,"");
	}
	
	/**
	 * 文件删除
	 * @param id 文件ID
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	@Log(module = "文件管理", operation = "删除文件")
    public Map<String, Object> delete(String id){
		FileUpload file = fileService.findById(id);
		fileService.delete(file);
		Ftp ftp = ftpService.findByOrganCode(SpringContextUtil.getMessage(Constants.行政区划));
		FtpUtils ft = new FtpUtils(ftp.getFtpip(), ftp.getFtpport(), ftp.getFtpuser(), ftp.getFtppassword());
		ft.delete(file.getRandomFileName(), "");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}
	
	  /**
     * 查询附件
	 * @author yangyd
	 * @param condition 
	 * @return
	 */
	@RequestMapping(value = "/query" , method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> query(FileUploadCondition condition){
		List<FileUpload> list = fileService.findAll(condition);
		Map<String,Object> map = new HashMap<String,Object>(); 
		map.put(CONTENT, list);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}
}